<template>
  <div style="width: 100%; height: 100%">
    <div :id="id" style="width: 100%; height: 100%"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { debounce } from "lodash";
export default {
  name: "chart-comp",
  props: {
    id: {
      type: String,
      default: "chart",
    },
    option: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      chartsIns: null,
      resizeHandler: null,
    };
  },
  watch: {
    option(val) {
      if (val) {
        this.chartsIns.setOption(val);
      }
    },
  },
  mounted() {
    this.initChart();
    this.bindResizeEvent();
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.resizeHandler);
    if (this.chartsIns) {
      this.chartsIns.dispose();
    }
  },
  methods: {
    initChart() {
      const chartDom = document.getElementById(this.id);
      const myChart = echarts.init(chartDom);
      this.chartsIns = myChart;
      this.chartsIns.setOption(this.option);
      const _this = this;
      this.chartsIns.on("click", function (params) {
        _this.$emit("chart-click", params);
      });
    },
    handleResize() {
      if (this.chartsIns) {
        this.chartsIns.resize();
      }
    },
    bindResizeEvent() {
      this.resizeHandler = debounce(this.handleResize, 500);
      window.addEventListener("resize", this.resizeHandler);
    },
  },
};
</script>
